package com.ywu.boot.interceptor.impl;

import com.ywu.boot.config.BootConfigAppConfig;
import com.ywu.boot.context.YwuContextRole;
import com.ywu.boot.context.YwuContext;
import com.ywu.boot.context.YwuContextHolder;
import com.ywu.boot.exception.YwuRuntimeException;
import com.ywu.boot.interceptor.ContextBuilderInterface;
import com.ywu.common.gson.GsonUtils;
import com.ywu.common.utils.AesUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @ClassName UserRoleContextBuilder
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/3/17 19:03
 * @Version 1.0
 **/
@Component
@Slf4j
@Order(5)
public class UserRoleContextBuilder implements ContextBuilderInterface {
    private static final String HEADER_KEY = "X-Pix-Ywu-User-Role";

    @Autowired
    private BootConfigAppConfig appConfig;

    @Override
    public void buildContext(HttpServletRequest request, HttpServletResponse response) {
        String userRoleInfo = request.getHeader(HEADER_KEY);
        // 解析上下文中加密的数据
        try {
            if (StringUtils.isEmpty(userRoleInfo)) {
                log.warn("UserRoleContextBuilder buildContext userRoleInfo is Empty");
                return;
            }
            String decryptUserInfo = AesUtils.decrypt(userRoleInfo, appConfig.getSecretKey());
            // 还原角色列表对象
            List<YwuContextRole> roles = GsonUtils.deserializeList(decryptUserInfo, YwuContextRole.class);
            YwuContext currentContext = YwuContextHolder.getCurrentContext();
            currentContext.setYwuContestRole(roles);
        } catch (Exception e) {
            log.error("UserInfoContextBuilder buildContext error {}", e.getMessage());
            throw new YwuRuntimeException(e.getMessage());
        }
    }

    @Override
    public String getBuildHeaderKey() {
        return HEADER_KEY;
    }
}
